package it.francescogabbrielli.android.solidalapp.actions;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.SolidalApp;

/**
 * Register to GCM and retry with exponential backoff 
 */
public class GCMRegisterDevice extends Action {
	
	private static final String PROJECT_NUMBER = "110637436951";
	
	private String id;
	
	private int retry;
	
	@Override
	public void execute() throws Exception {
		retry = getIntent().getIntExtra("retry", 0);
		id = GoogleCloudMessaging.getInstance(context).register(PROJECT_NUMBER);
		Log.d(getClass().getSimpleName(), "Registered to GCM: "+id);
	}
	
	@Override
	public void onError(String error) {
		Log.i(SolidalApp.TAG, "Error registering: "+error);
		tryAgain();
	}

	@Override
	public void onPostExecute() throws Exception {
		// store gcm id
		if (id!=null) {
			app.getStatus().setGcmId(id);
			app.registerToServices();
		// try again
		} else if (retry<5)
			tryAgain();
	}
	
	private void tryAgain() {
		final int n = retry+1;
		int backoff = (int) Math.pow(2, n); 
		Log.i(SolidalApp.TAG, "Retry registration in "+backoff+"s...");
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				if (app.getStatus().getGcmId()==null) {
					Bundle data = new Bundle();
					data.putInt("retry", n);
					Action.start(context, GCMRegisterDevice.class, data);
				}
			}
		}, backoff * 1000l);
	}

}
